// 导入高德地图适配器
const amapAdapter = require('../../utils/amapwx-adapter.js');

Page({
  data: {
    // 地图中心点
    latitude: 22.684812,
    longitude: 112.779762,
    scale: 14,
    markers: [],
    // 权限状态
    hasLocationAuth: false,
    // 加载状态
    loading: false,
    loadingText: '',
    // 当前位置信息
    currentLocation: null,
    showLocationInfo: false,
    // POI信息
    currentPOI: null,
    showPOIInfo: false
  },

  onLoad: function() {
    // 检查位置权限
    this.checkLocationAuth();
  },
  
  // 检查位置权限
  checkLocationAuth: function() {
    wx.getSetting({
      success: (res) => {
        const hasLocationAuth = res.authSetting['scope.userLocation'];
        this.setData({
          hasLocationAuth: hasLocationAuth
        });
        
        if (hasLocationAuth) {
          this.getCurrentLocation();
        }
      }
    });
  },
  
  // 申请位置权限
  requestLocationAuth: function() {
    this.setData({ loading: true, loadingText: '获取位置权限中...' });
    
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.setData({
          hasLocationAuth: true
        });
        this.getCurrentLocation();
      },
      fail: (err) => {
        console.error('位置权限获取失败', err);
        wx.showToast({
          title: '获取位置权限失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },
  
  // 打开设置页面
  openSettings: function() {
    wx.openSetting({
      success: (res) => {
        this.setData({
          hasLocationAuth: res.authSetting['scope.userLocation']
        });
        
        if (res.authSetting['scope.userLocation']) {
          this.getCurrentLocation();
        }
      }
    });
  },
  
  // 获取当前位置
  getCurrentLocation: function() {
    if (!this.data.hasLocationAuth) {
      return;
    }
    
    this.setData({ loading: true, loadingText: '获取位置中...' });
    
    amapAdapter.getCurrentLocation()
      .then(location => {
        const { latitude, longitude } = location;
        
        // 更新地图中心点
        this.setData({
          latitude,
          longitude,
          markers: [{
            id: 0,
            latitude,
            longitude,
            iconPath: '/static/images/location.png',
            width: 32,
            height: 32
          }]
        });
        
        // 获取位置详细信息
        return amapAdapter.reverseGeocode(latitude, longitude);
      })
      .then(data => {
        if (data) {
          this.setData({
            currentLocation: {
              latitude: this.data.latitude,
              longitude: this.data.longitude,
              address: data.address,
              name: data.name,
              district: data.district,
              city: data.city
            },
            showLocationInfo: true
          });
        }
      })
      .catch(err => {
        console.error('获取位置失败', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },
  
  // 搜索附近POI
  searchNearby: function(e) {
    const type = e.currentTarget.dataset.type || '';
    
    this.setData({ loading: true, loadingText: '搜索中...' });
    
    amapAdapter.searchNearby({
      location: {
        latitude: this.data.latitude,
        longitude: this.data.longitude
      },
      type: type,
      radius: 2000,
      limit: 20
    })
      .then(pois => {
        if (pois && pois.length > 0) {
          // 处理标记点
          const markers = pois.map((item, index) => {
            return {
              id: index + 1,
              latitude: item.latitude,
              longitude: item.longitude,
              title: item.name,
              iconPath: '/static/images/marker.png',
              width: 32,
              height: 32,
              callout: {
                content: item.name,
                color: '#000000',
                fontSize: 14,
                borderRadius: 4,
                bgColor: '#ffffff',
                padding: 8,
                display: 'BYCLICK'
              }
            };
          });
          
          // 添加当前位置标记
          markers.unshift({
            id: 0,
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            iconPath: '/static/images/location.png',
            width: 32,
            height: 32
          });
          
          this.setData({ markers });
          
          if (pois.length === 0) {
            wx.showToast({
              title: '附近没有找到相关地点',
              icon: 'none'
            });
          }
        }
      })
      .catch(err => {
        console.error('搜索POI失败', err);
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },
  
  // 点击标记点
  markerTap: function(e) {
    const markerId = e.markerId;
    
    // 跳过当前位置标记
    if (markerId === 0) {
      return;
    }
    
    const marker = this.data.markers.find(item => item.id === markerId);
    if (marker) {
      // 获取POI详细信息
      this.setData({
        currentPOI: {
          name: marker.title,
          latitude: marker.latitude,
          longitude: marker.longitude,
          address: '正在获取地址...',
          distance: this.calculateDistance(
            this.data.latitude,
            this.data.longitude,
            marker.latitude,
            marker.longitude
          )
        },
        showPOIInfo: true
      });
      
      // 获取详细地址
      amapAdapter.reverseGeocode(marker.latitude, marker.longitude)
        .then(data => {
          if (data) {
            this.setData({
              'currentPOI.address': data.address || '未知地址'
            });
          }
        })
        .catch(err => {
          console.error('获取地址失败', err);
          this.setData({
            'currentPOI.address': '地址获取失败'
          });
        });
    }
  },
  
  // 关闭位置信息
  closeLocationInfo: function() {
    this.setData({
      showLocationInfo: false
    });
  },
  
  // 关闭POI信息
  closePOIInfo: function() {
    this.setData({
      showPOIInfo: false
    });
  },
  
  // 导航到POI
  navigateToPOI: function() {
    const poi = this.data.currentPOI;
    if (!poi) return;
    
    this.setData({ loading: true, loadingText: '规划路线中...' });
    
    amapAdapter.calculateRoute({
      origin: {
        latitude: this.data.latitude,
        longitude: this.data.longitude
      },
      destination: {
        latitude: poi.latitude,
        longitude: poi.longitude
      },
      mode: 'walking'
    })
      .then(routeData => {
        console.log('路线数据', routeData);
        
        wx.openLocation({
          latitude: poi.latitude,
          longitude: poi.longitude,
          name: poi.name,
          address: poi.address,
          scale: 18
        });
      })
      .catch(err => {
        console.error('导航失败', err);
        wx.showToast({
          title: '导航失败',
          icon: 'none'
        });
        
        // 直接打开内置导航
        wx.openLocation({
          latitude: poi.latitude,
          longitude: poi.longitude,
          name: poi.name,
          address: poi.address,
          scale: 18
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },
  
  // 计算两点之间的距离（米）
  calculateDistance: function(lat1, lon1, lat2, lon2) {
    const EARTH_RADIUS = 6371000; // 地球半径，单位：米
    
    // 经纬度转换为弧度
    const toRadians = (degrees) => {
      return degrees * Math.PI / 180;
    };
    
    const lat1Rad = toRadians(lat1);
    const lon1Rad = toRadians(lon1);
    const lat2Rad = toRadians(lat2);
    const lon2Rad = toRadians(lon2);
    
    // Haversine公式
    const dLat = lat2Rad - lat1Rad;
    const dLon = lon2Rad - lon1Rad;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1Rad) * Math.cos(lat2Rad) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = EARTH_RADIUS * c;
    
    return distance;
  }
}); 